package top.zxybird.common.query;

import java.util.ArrayList;
import java.util.List;

/**
 * BooleanQuery.
 * 
 * Created by zxybird on 2017/11/16.
 */
public abstract class BooleanQuery extends Query {
  protected BooleanQuery.Occur occur;
  protected List<Query> booleanClauses = new ArrayList();

  protected BooleanQuery(BooleanQuery.Occur occur) {
    this.occur = occur;
  }

  public BooleanQuery addQuery(Query query) {
    this.booleanClauses.add(query);
    return this;
  }

  public String toString() {
    if (this.booleanClauses.isEmpty()) {
      return null;
    } else {
      StringBuilder stringBuilder = new StringBuilder(256);
      if (this.booleanClauses.size() == 1) {
        stringBuilder.append(this.booleanClauses.get(0));
      } else {
        stringBuilder.append('(');

        for (int i = 0; i < this.booleanClauses.size(); ++i) {
          if (i > 0) {
            stringBuilder.append(" ").append(this.occur).append(" ");
          }

          stringBuilder.append(this.booleanClauses.get(i));
        }

        stringBuilder.append(')');
      }

      return stringBuilder.toString();
    }
  }

  public static enum Occur {
    AND, OR;

    private Occur() {
    }
  }
}
